package com.compass.doctor.ui.home

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.DisplayMetrics
import android.widget.LinearLayout
import com.compass.doctor.R
import com.compass.doctor.databinding.ActivityFollowUpBinding
import com.compass.doctor.utils.ChartUtils
import com.compass.doctor.utils.MyValueFormatter
import com.compass.doctor.base.BaseVBActivity
import com.compass.framework.ext.onClick
import com.compass.framework.model.AgeCount
import com.compass.framework.model.PatientCount
import com.compass.framework.model.QuestionnaireRate
import com.compass.framework.utils.StatusBarSettingHelper
import com.compass.framework.utils.getColorDrawable
import com.compass.framework.utils.getColorFromResource
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.charts.PieChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.PercentFormatter
import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet

/**
 * Description： 慢病随访
 * Date:2023/12/13 9:16
 */
class FollowUpActivity : BaseVBActivity<ActivityFollowUpBinding>() {

    private val colors = intArrayOf(
        Color.rgb(92, 141, 242),
        Color.rgb(246, 139, 17),
        Color.rgb(249, 224, 195),
        Color.rgb(255, 97, 138),
        Color.rgb(255, 255, 255),
        Color.rgb(239, 82, 46)
    )

    private val diseasesColors = intArrayOf(
        Color.rgb(246, 139, 17),
        Color.rgb(163, 168, 240),
        Color.rgb(11, 191, 53),
        Color.rgb(255, 97, 138),
        Color.rgb(97, 190, 255),
        Color.rgb(239, 169, 46),
        Color.rgb(92, 240, 242),
        Color.rgb(172, 191, 11),
        Color.rgb(97, 190, 255),
        Color.rgb(92, 146, 255),
        Color.rgb(117, 92, 242),
        Color.rgb(11, 191, 155),
        Color.rgb(64, 222, 190),
        Color.rgb(184, 92, 242),
        Color.rgb(92, 103, 242),
        Color.rgb(92, 141, 242),
        Color.rgb(246, 216, 17),
        Color.rgb(239, 82, 46)
    )
    private val animateTime = 1000

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, FollowUpActivity::class.java)
            context.startActivity(intent)
        }
    }
    override fun initView(savedInstanceState: Bundle?) {
        StatusBarSettingHelper.setStatusBarTranslucent(this)
        StatusBarSettingHelper.statusBarLightMode(this@FollowUpActivity, true)
        ChartUtils.initBarChart(mBinding.chartPlan)
        ChartUtils.initLineChart(mBinding.lineChart)
        ChartUtils.initHalfPieChart(mBinding.pieChart)
    }

    override fun initData() {
        setBarChatData()
        setLineChartData()
        setAgePieChartData()
    }

    override fun intListener() {
          mBinding.tvMore.onClick {
              FollowUpPatientActivity.start(this)
          }
    }


    private fun setBarChatData() {
        mBinding.chartPlan.animateY(animateTime, Easing.EaseInOutQuad)

        val questionnaireRates: ArrayList<QuestionnaireRate> = ArrayList()
        questionnaireRates.add(QuestionnaireRate(10f, "胃癌", 5f))
        questionnaireRates.add(QuestionnaireRate(15f, "直肠癌", 13f))
        questionnaireRates.add(QuestionnaireRate(15f, "肺癌", 10f))
        questionnaireRates.add(QuestionnaireRate(18f, "胰岛癌", 3f))
        questionnaireRates.add(QuestionnaireRate(12f, "卵巢癌", 8f))
        if (questionnaireRates.isEmpty()) {
            return
        }
        val values = ArrayList<BarEntry>()
        var maxNumber = 0f
        var fillCount = 0f
        var number: Float
        var number2: Float
        for (i in questionnaireRates.indices) {
            number = questionnaireRates[i].fillCount!!
            number2 = questionnaireRates[i].noFillCount!!
            fillCount = number + number2
            if (maxNumber < fillCount) {
                maxNumber = fillCount
            }
            values.add(BarEntry(i.toFloat(), floatArrayOf(number, number2)))
        }
        // 左右空出barWidth/2，更美观
        mBinding.chartPlan.setFitBars(true)
        //设置Y轴最大值比集合最大值大5
        mBinding.chartPlan.axisLeft.axisMaximum = maxNumber + 5
        // 设置x轴显示在下方
        mBinding.chartPlan.xAxis.position=XAxis.XAxisPosition.BOTTOM
        //设置x轴最大显示数量
        mBinding.chartPlan. xAxis.setLabelCount(questionnaireRates.size, false)
        //X轴自定义值
        mBinding.chartPlan.xAxis.valueFormatter = (object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                var position = value.toInt()
                return questionnaireRates[position].name
            }
        })


        val set1 = BarDataSet(values, "")
        set1.setDrawIcons(false)
        set1.setColors(colors[1], colors[2])
        set1.stackLabels = arrayOf("已完成问卷占比(F)", "未完成问卷占比(U)")
        set1.valueTextSize = 12f
        set1.isHighlightEnabled = false
        val dataSets = ArrayList<IBarDataSet>()
        dataSets.add(set1)
        val data = BarData(dataSets)
        data.setValueFormatter(MyValueFormatter())
        data.setValueTextColor(Color.BLACK)
        val barWidth = 0.5f
        data.barWidth = barWidth
        mBinding.chartPlan.data = data
        //        chartPatients.setFitBars(true);
        mBinding.chartPlan.invalidate()
    }


    private fun setLineChartData() {
        mBinding.lineChart.animateY(animateTime, Easing.EaseInOutQuad)


        val patientCount: ArrayList<PatientCount> = ArrayList()
        patientCount.add(PatientCount("","0"))
        patientCount.add(PatientCount("1月","5"))
        patientCount.add(PatientCount("2月","15"))
        patientCount.add(PatientCount("3月","23"))
        patientCount.add(PatientCount("4月","12"))
        patientCount.add(PatientCount("5月","19"))
        if (patientCount.isEmpty()) {
            return
        }
        val values = java.util.ArrayList<Entry>()
        var sum = 0
        var maxNumber = 0
        var count: Int
        for (i in patientCount.indices) {
            count = Integer.valueOf(patientCount[i].count)
            if (maxNumber < count) {
                maxNumber =count
            }
            values.add(Entry(i.toFloat(), count.toFloat()))
            sum = count
        }
        //设置Y左边轴显示的值 label 数量
        mBinding.lineChart.axisLeft.setLabelCount(patientCount.size, true)
        //设置x轴最大显示数量
        mBinding.lineChart.xAxis.setLabelCount(patientCount.size, true)
        //设置Y轴最大值比集合最大值大5
        mBinding.lineChart.axisLeft.axisMaximum = (maxNumber + 5).toFloat()
        mBinding.lineChart.xAxis.valueFormatter = (object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                var position = value.toInt()
                return patientCount[position].date
            }
        })
        val set1 = LineDataSet(values, "目前总患者数为：$sum")
        set1.setDrawIcons(false)
        set1.mode = LineDataSet.Mode.CUBIC_BEZIER
        set1.lineWidth = 1.75f
        set1.circleRadius = 5f
        set1.circleHoleRadius = 2.5f
        set1.color = colors[0]
        set1.setCircleColor(colors[0])
        set1.highLightColor = colors[0]
        set1.setDrawCircleHole(true)
        val drawable = getColorDrawable(R.color.bg_blue)
        set1.fillDrawable = drawable
        set1.setDrawFilled(true)
        set1.valueTextSize = 12f
        set1.valueTextColor = getColorFromResource(R.color.color_2e344a)
        val dataSets = ArrayList<ILineDataSet>()
        dataSets.add(set1)
        val data = LineData(dataSets)
        data.setValueFormatter(MyValueFormatter())
        mBinding.lineChart.data = data
    }

    private fun setAgePieChartData() {
        mBinding.pieChart.setDrawEntryLabels(false)
        mBinding.pieChart.animateY(animateTime, Easing.EaseInOutQuad)
        moveOffScreen(mBinding.pieChart)
        val ageCounts: ArrayList<AgeCount> = ArrayList()
        ageCounts.add(AgeCount("1~10(岁)",5))
        ageCounts.add(AgeCount("10~30(岁)",8))
        ageCounts.add(AgeCount("31~40(岁)",10))
        ageCounts.add(AgeCount("41~60(岁)",20))
        if (ageCounts.isEmpty()) {
            return
        }
        val entries = ArrayList<PieEntry>()
        for (i in ageCounts.indices) {
            entries.add( PieEntry(  ageCounts[i].value.toFloat(),  ageCounts[i].key))
        }
        val dataSet = PieDataSet(entries, "")
        dataSet.sliceSpace = 3f
        dataSet.selectionShift = 5f
        dataSet.valueTextSize = 12f
        dataSet.setColors(colors[0], colors[3], colors[5])
        val data = PieData(dataSet)
        data.setValueFormatter(PercentFormatter())
        data.setValueTextSize(12f)
        data.setValueTextColor(Color.WHITE)
        mBinding.pieChart.data = data
        mBinding.pieChart.invalidate()
    }

    private fun moveOffScreen(chart: PieChart) {
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        val height = displayMetrics.heightPixels
        val offset = (height * 0.20).toInt() /* percent to move */
        val rlParams = chart.layoutParams as LinearLayout.LayoutParams
        rlParams.setMargins(0, 0, 0, -offset)
        chart.layoutParams = rlParams
    }
}